package edu.cuit.campus.admin.controller;

import edu.cuit.campus.admin.service.AdministratorService;
import edu.cuit.campus.admin.service.bean.AdministratorServiceBean;
import edu.cuit.campus.commons.annotations.Controller;
import edu.cuit.campus.commons.annotations.RequestMapping;
import edu.cuit.campus.commons.annotations.ResponseBody;
import edu.cuit.campus.commons.response.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/8/11 15:52
 */
@Controller
@RequestMapping("/administrators")
public class AdministratorController {
    private AdministratorService service = new AdministratorServiceBean();
    @RequestMapping("/login")
    @ResponseBody
    public Result login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        var username = request.getParameter("username");
        var password = request.getParameter("password");
        var admin = service.login(username, password);
        if(admin != null){
            request.getSession().setAttribute("administrator", admin);
            return Result.ok(admin.getUsername());
        }
        return Result.fail();
    }

    @RequestMapping("/logout")
    @ResponseBody
    public Result logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getSession().invalidate();
        return Result.ok();
    }
}
